<?php


namespace Api\Controller;
use Think\Controller;
use Think\Page;
/*
 * 新先到先得控制器
 * */
class SpellGoodsController extends BaseController
{
	
	public function  __construct() 
	{   
        parent::__construct();
    }
	
	/**
	 * 商品数据
	 */
	public function goodsList(){
		$p = I('p', 1, 'intval');
		// 组合筛选条件
		$where_goods_list['is_on_sale'] = 1;
		$goods_list = M('spell_goods')->where($where_goods_list)->page($p,10)->order('sort desc')->select();
		
		// 对查询数据进行处理
		foreach($goods_list as $k => &$v){
			$v['original_img'] = parseMediaUrl($v['original_img']);
			// 查询进行中的活动
			$where_project['spell_goods_id'] = $v['spell_goods_id'];
			$where_project['conduct_end_time'] = ['EGT',\time()];
			$where_project['state'] = 1;
			$project = M('spell_project')->where($where_project)->find();
			$v['project'] = $project;
		}
		
		$this->returnInfo('1','商品获取成功',['goods_list'=>$goods_list]);  
	}
	
	
	/**
	 * 给参与者扣分
	 */
	public function deduction_spell_project_user_point(){
		// 查询用户参与的活动
		$where_recharge_order['order_sn'] = 'rechargebyClHs56Dg';
		$order = M('recharge')->where($where_recharge_order)->find();
		
		$user_id = $this->user_id;
		$spell_project_id = I('spell_project_id');
		$spell_project_user_id = I('spell_project_user_id');
		$where_user_project_user['sp.spell_project_id'] = $spell_project_id;
		$where_user_project_user['sp.state'] = 1;
		
		$where_user_project_user['sp.conduct_end_time'] = ['GT',\time()-3*60*60*24];
		$spell_project_user = M('spell_project_user')->alias('spu')->where($where_user_project_user)
		->join('__SPELL_PROJECT__ as sp ON sp.spell_project_id = spu.spell_project_id')->field('sp.*,spu.point')
		->find();
	
		// 对参活动数据进行处理
		if($spell_project_user){
			// 查询用户信息
			$user_info = M('users')->where(['user_id'=>$user_id])->find();
			// 分割用户标识id
			$user_id_array = \explode(',',$spell_project_user_id);
			// p($user_id_array);die;
			foreach($user_id_array as $k => $v){
				// p($v);
				// 查询可用扣分机会
				$where_deduction_point['spell_project_id'] = $spell_project_id;
				$where_deduction_point['user_id'] = $user_id;
				$where_deduction_point['use_user_id'] = 0;
				$deduction_point = M('spell_project_user_skill')->where($where_deduction_point)->find();
				// p($deduction_point);die;
				if($v && $deduction_point){
					// 添加扣除记录
					$user_point_log['spell_project_id'] = $spell_project_id;
					$user_point_log['users_id'] = $v;
					$user_point_log['order_id'] = 0;
					$user_point_log['pay_money'] = 0;
					$user_point_log['add_time'] = time();
					$user_point_log['content'] = '被用户'.$user_info['nickname'].'扣除'.$deduction_point['dec_point'].'分';
					$user_point_log['type'] = 2;
					$user_point_log['point'] = $deduction_point['dec_point'];
					M('spell_project_point_log')->add($user_point_log);
					
					// p($deduction_point);p($v);die;
					M('spell_project_user_skill')->save(['use_user_id'=>$v,'last_update'=>time(),'id'=>$deduction_point['id']]);
				}
			}
			$this->returnInfo('1','扣分成功');
		
		}else{
			$this->returnInfo('-1','无此参与活动');
		}
		
	}
	
	/**
	 * 获取活动参与人
	 */
	public function get_spell_project_people(){
		// 查询用户参与的活动
		$user_id = $this->user_id;
		$spell_project_id = I('spell_project_id');
		$where_user_project_user['sp.spell_project_id'] = $spell_project_id;
		$where_user_project_user['sp.state'] = 1;
		$where_user_project_user['sp.conduct_end_time'] = ['GT',\time()-3*60*60*24];
		$spell_project_user = M('spell_project_user')->alias('spu')->where($where_user_project_user)
		->join('__SPELL_PROJECT__ as sp ON sp.spell_project_id = spu.spell_project_id')->field('sp.*,spu.point')
		->find();

		// 对参活动数据进行处理
		if($spell_project_user){
		
			$activity_information = [];
			$activity_information['active_value'] = \rand(60,90);

			$top_list = get_spell_top_list($spell_project_user['spell_project_id']);
			$activity_information['top_list'] = $top_list;
			$spell_project_user['activity_information'] = $activity_information;
		
		}else{
			$this->returnInfo('-1','无此参与活动');
		}
		
		$this->returnInfo('1','当前活动获取成功',['spell_project_user'=>$spell_project_user]);
	}
	
	/**
	 * 修改活动实效阅读
	 */
	public function save_project_user(){
		// 查询用户参与的活动
		$user_id = $this->user_id;
		$spell_project_id = I('spell_project_id');
		$where_user_project_user['sp.spell_project_id'] = $spell_project_id;
		$where_user_project_user['spu.user_id'] = $user_id;
		
		$where_user_project_user['sp.conduct_end_time'] = ['GT',\time()-3*60*60*24];
		$spell_project_user = M('spell_project_user')->alias('spu')->where($where_user_project_user)
		->join('__SPELL_PROJECT__ as sp ON sp.spell_project_id = spu.spell_project_id')->field('sp.*,spu.point,spu.state as spustate,spu.id as spuid')
		->find();
	
		// 对参活动数据进行处理
		if($spell_project_user){
			// 修改本活动为已经查阅
			if($spell_project_user['spustate'] ==1){
				$save_project_user['state'] = 0;
				if(M('spell_project_user')->where(['id'=>$spell_project_user['spuid']])->save($save_project_user)){
					$this->returnInfo('1','修改成功');
				}else{
					$this->returnInfo('-1','修改失败');
				}
			}else{
				$this->returnInfo('-1','状态已经修改');
			}
		}else{
			$this->returnInfo('-1','无此参与活动');
		}
		
		
	}
	
	/**
	 * 获取当前用户参与活动信息
	 */
	public function activity_information(){
		// 查询用户参与的活动
		$user_id = $this->user_id;
		$spell_project_id = I('spell_project_id');
		if($spell_project_id){
			$where_user_project_user['sp.spell_project_id'] = $spell_project_id;
			$where_user_project_user['sp.wait_end_time'] = ['ELT',time()];
		}else{
			if(!$user_id){

				return $this->returnInfo(-100, "请先登录");
			}
			$where_user_project_user['spu.user_id'] = $user_id;
		}
		$otime = time();
		$where_user_project_user['spu.state'] = 1;
		$where_user_project_user['sp.conduct_end_time'] = ['GT',$otime-3*60*60*24];
		$spell_project_user = M('spell_project_user')->alias('spu')->where($where_user_project_user)
		->join('__SPELL_PROJECT__ as sp ON sp.spell_project_id = spu.spell_project_id')->field('sp.*,spu.point')
		->find();
		// p($spell_project_user);die;
		update_spell_project($spell_project_user['spell_project_id'],$user_id);
		// 对参活动数据进行处理
		if($spell_project_user){
			// 查询活动参加人数
			$where_project_user_count['spell_project_id'] = $spell_project_user['spell_project_id'];
			$project_user_count = M('spell_project_user')->where($where_project_user_count)->count();
			
			// p($available_time);die;
			$wait_loding_time = 0;
			
			if($spell_project_user['wait_end_time'] > $otime){
				$wait_loding_time = ($spell_project_user['wait_end_time'] - $otime)/3600;
			}
			$spell_project_user['wait_loding_time'] = intval($wait_loding_time);
			$conduct_loding_time = 0;
			if($spell_project_user['conduct_end_time'] >= $otime){
				$conduct_loding_time = ($spell_project_user['conduct_end_time'] - $otime)/3600;
			}
			$spell_project_user['conduct_loding_time'] = intval($conduct_loding_time);
			$spell_project_user['project_user_count'] = $project_user_count;
			// 转换时间
			$spell_project_user['wait_start_time_str'] = date('Y-m-d',$spell_project_user['wait_start_time']);
			$spell_project_user['wait_end_time_str'] = date('Y-m-d',$spell_project_user['wait_end_time']);
			$spell_project_user['conduct_end_time_str'] = date('Y-m-d',$spell_project_user['conduct_end_time']);
			// 查询商品信息
			if($wait_loding_time == 0 && $conduct_loding_time != 0){
				$activity_information = [];
				$activity_information['active_value'] = $spell_project_user['activity_level'];
				
				// 查询现有三档排行
				
				$top_list = get_spell_top_list($spell_project_user['spell_project_id']);
				// p($top_list);die;
				$activity_information['top_list'] = $top_list;
				$spell_project_user['activity_information'] = $activity_information;
			}
			
			// 查询商品信息
			
			if($conduct_loding_time == 0){
				$activity_settlement_information = [];
				
				$where_spell_top_list['spell_project_id'] = $spell_project_user['spell_project_id'];
				$top_list = M('spell_project_user')->where($where_spell_top_list)->limit(3)->order('point DESC')->select();
				foreach($top_list as $k => &$v){
					$v['shopping_value'] = \intval(M('spell_project_point_log')->where(['spell_project_id'=>$spell_project_user['spell_project_id'],'users_id'=>$v['user_id'],'type'=>0])->sum('point'));
					$v['recharge_value'] = \intval(M('spell_project_point_log')->where(['spell_project_id'=>$spell_project_user['spell_project_id'],'users_id'=>$v['user_id'],'type'=>1])->sum('point'));
					$v['deduction_list'] = M('spell_project_point_log')->where(['spell_project_id'=>$spell_project_user['spell_project_id'],'users_id'=>$v['user_id'],'type'=>2])->select();
					$deduction_value = 0;
					foreach($v['deduction_list'] as $ks => &$vs){
						$vs['add_time_str'] = date('m-d H:i',$vs['add_time']);
						$deduction_value += $vs['point'];
					}
					$v['deduction_value'] = $deduction_value;
					
				}
				// 购买状态
				$where_spell_order['spell_project_id'] = $spell_project_user['spell_project_id'];
				$spell_order = M('spell_order')->where($where_spell_order)->find();
				$activity_settlement_information['purchase_state'] = isset($spell_order)?1:0;
				$activity_settlement_information['top_list'] = $top_list;
				$spell_project_user['activity_settlement_information'] = $activity_settlement_information;
			}
			$where_goods_data['spell_goods_id'] = $spell_project_user['spell_goods_id'];
			$spell_project_user['goods_data'] = M('spell_goods')->where($where_goods_data)->find();
			$spell_project_user['goods_data']['original_img'] = parseMediaUrl($spell_project_user['goods_data']['original_img']);
			// 查询用户最新积分
			$where_user_point['spell_project_id'] = $spell_project_user['spell_project_id'];
			$where_user_point['user_id'] = $user_id;
			$spell_project_user['point'] = M('spell_project_user')->where($where_user_point)->find()['point'];
			$this->returnInfo('1','当前活动获取成功',['spell_project_user'=>$spell_project_user]);
		}else{
			$this->returnInfo('-1','无此参与活动');
		}
		
		
	}
	
	/**
	 * 创建活动
	 */
	public function add_project(){
		$goods_id = I('goods_id', 1, 'intval');// 商品id
		$project_id = I('project_id');// 活动id
		$user_id = $this->user_id;
		
		// 查询用户活动参与情况
		$where_user_project_user['spu.user_id'] = $user_id;
		$where_user_project_user['sp.state'] = 1;
		$where_user_project_user['sp.conduct_end_time'] = ['GT',\time()];
		$spell_project_user = M('spell_project_user')->alias('spu')->where($where_user_project_user)
		->join('__SPELL_PROJECT__ as sp ON sp.spell_project_id = spu.spell_project_id')->field('sp.*,spu.point')
		->find();
		if($spell_project_user){
			$this->returnInfo('-1','账号已经参加活动');
		}
		// 查询当前活动状态
		if($project_id){
			$where_spell_project['spell_project_id'] = $project_id;
			$where_spell_project['conduct_end_time'] = ['GT',\time()];
			$spell_project = M('spell_project')->where($where_spell_project)->find();
			
			if(!spell_project){
				$this->returnInfo('-1','无此活动');
			}
			// 检测是否是可用
			if($spell_project['wait_end_time'] <= \time()){
				$this->returnInfo('-1','活动已经开始不能参加。');
			}
			$goods_id = $spell_project['spell_goods_id'];
			// 查询活动参与人数 用户补丁遗漏数据
			if($spell_project['need_number'] <= M('spell_project_user')->where(['spell_project_id'=>$spell_project['spell_project_id']])->count()){
				// 开始次活动
				$where_project_goods['spell_goods_id'] = $goods_id;
				$where_project_goods['is_on_sale'] = 1;
				$project_goods = M('spell_goods')->where($where_project_goods)->find();
				$save_spell_project['wait_end_time'] = \time();
				$save_spell_project['last_update'] = \time();
				$save_spell_project['last_update'] = \time();
				$save_spell_project['conduct_end_time'] = \time()+(60*60*24*$project_goods['conduct_time']);
				M('spell_project')->where(['spell_project_id'=>$project_id])->save($save_spell_project);
				$this->returnInfo('-1','活动人数已经满足。');
			}
			
		}
		// 查询商品信息
		$where_project_goods['spell_goods_id'] = $goods_id;
		$where_project_goods['is_on_sale'] = 1;
		$project_goods = M('spell_goods')->where($where_project_goods)->find();
		if(!$project_goods){
			$this->returnInfo('-1','无此商品');
		}
		if(!$spell_project){
			if(!$spell_project){
				// 查询一个可供参与的活动
				$spell_project_list = M('spell_project')->where(['wait_end_time'=> ['EGT',time()],'settlement_user_id'=>0])->find();
				
				$where_spell_project['spell_goods_id'] = $goods_id;
				$where_spell_project['conduct_end_time'] = ['GT',\time()];
				$spell_project_list = M('spell_project')->where($where_spell_project)->select();
				// p($spell_project_list);die;
				foreach($spell_project_list as $k => $v){
					// 查询人数是否满足
					if($v['need_number'] <= M('spell_project_user')->where(['spell_project_id'=>$v['spell_project_id']])->count()){
						// 开始次活动
						$where_project_goods['spell_goods_id'] = $goods_id;
						$where_project_goods['is_on_sale'] = 1;
						$project_goods = M('spell_goods')->where($where_project_goods)->find();
						$save_spell_project['wait_end_time'] = \time();
						$save_spell_project['last_update'] = \time();
						$save_spell_project['conduct_end_time'] = \time()+60*60*24*$project_goods['conduct_time'];
						
						M('spell_project')->where(['spell_project_id'=>$project_id])->save($save_spell_project);
					}else{
						$spell_project = $v;
					}
				}
			}
			// p($spell_project);die;
			if($spell_project){
				$project_id = $spell_project_id = $spell_project['spell_project_id'];
			}else{
				// 查询消费金额
				$where_order['user_id'] = $user_id;
				$where_order['pay_status'] = 1;
				// $where_order['parent_sn'] = '';
				$where_order['total_amount'] = ['GT',60];
				if(!M('order')->where($where_order)->find()){
					$this->returnInfo('-1','不满足参与资格');
				}
				$time = \time();
				$add_spell_project['spell_goods_id'] = $project_goods['spell_goods_id'];
				$add_spell_project['user_id'] = $user_id;
				$add_spell_project['wait_start_time'] = $time;
				$add_spell_project['wait_end_time'] = $wait_end_time = $time+(60*60*24*$project_goods['wait_time']);
				$add_spell_project['conduct_end_time'] = $wait_end_time+(60*60*24*$project_goods['conduct_time']);
				$add_spell_project['need_number'] = $project_goods['need_number'];
				$add_spell_project['last_update'] = \time();
				// p($add_spell_project);die;
				$project_id = $spell_project_id = M('spell_project')->add($add_spell_project);
				
			}
		}
		if($project_id && $goods_id){
			// 查询用户参加情况
			$where_project_user['spell_project_id'] = $project_id;
			$where_project_user['user_id'] = $user_id;
			if(M('spell_project_user')->where($where_project_user)->find()){
				$this->returnInfo('-1','请勿重复参加');
			}else{
				// 查询用户信息
				$where_user['user_id'] = $user_id;
				$user_info = M('users')->where($where_user)->find();
				if(!$user_info){
					$this->returnInfo('-100','请先登录');
				}
				$where_project_user['point'] = 0;
				$where_project_user['add_time'] = \time();
				$where_project_user['last_update'] = \time();
				$where_project_user['nickname'] = $user_info['nickname'];
				if(M('spell_project_user')->add($where_project_user)){
					// 查询活动参与人数 用户补丁遗漏数据
					$need_number = M('spell_project_user')->where(['spell_project_id'=>$project_id])->count();
					$where_spell_project['spell_project_id'] = $project_id;
					$spell_project = M('spell_project')->where($where_spell_project)->find();
					if($spell_project['need_number'] <= $need_number){
						// 开始次活动
						$save_spell_project['wait_end_time'] = \time();
						$save_spell_project['last_update'] = \time();
						$save_spell_project['conduct_end_time'] = \time()+60*60*24*$project_goods['conduct_time'];
						// p($save_spell_project);die;
						M('spell_project')->where(['spell_project_id'=>$project_id])->save($save_spell_project);
						$this->returnInfo('1','成功参加成功，活动开启成功。');
					}
					$this->returnInfo('1','参加成功');
				}else{
					$this->returnInfo('-1','参加失败');
				}
			}
		}else{
			$this->returnInfo('-1','数据不全');
		}
	}
	
	/**
	 * 商品购买核对
	 */
	public function purchaseCheck(){
		$spell_project_id = I('spell_project_id',0,'intval'); // 当前单独商品
		$usersInfo = get_user_info($this->user_id);  // 用户
		if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));
	
		// 收货地址
		$addresslist = M('UserAddress')
		->where(["user_id"=>$this->user_id])
		->order("is_default desc")
		->limit(1)
		->select();
		// 获取活动信息
		$where_spell_project['spell_project_id'] = \intval($spell_project_id);
		$where_spell_project['settlement_user_id'] = $this->user_id;
		$where_spell_project['state'] = 1;
		if(!$spell_project = M('spell_project')->where($where_spell_project)->find()){
			$this->returnInfo(-1,"无此活动");
		}
		$goods_id = $spell_project['spell_goods_id'];
		// 获取商品信息
		$where['is_on_sale'] = 1;
		if($goods_id)$where['spell_goods_id'] = intval($goods_id);
		
		$goods_list = M('spell_goods')->where($where)->select();
		foreach($goods_list as $k => &$v){
			$v['original_img'] = parseMediaUrl($v['original_img']);
		}
		if(count($goods_list) <= 0) exit(json_encode(array('status' => -1, 'msg' => '无此商品信息', 'result' => '')));
		if($goods_id && count($goods_list) == 1)$goods_list = $goods_list[0];
		
		$json_arr = array(
		    'status' => 1,
		    'msg' => '获取成功',
		    'result' => array(
		        'addressList' => $this->getAddressInfo($addresslist), // 收货地址
		        'goodsList' => $goods_list, // 商品信息
		        'userInfo' => $usersInfo?$usersInfo:[], // 用户详情
		    )
		);
		exit(json_encode($json_arr));
	}
	/**
	 * 先到先得商品下单
	 */
	public function buyGoods(){
		// 检测商品状态
		$spell_project_id = I('spell_project_id',0,'intval'); // 当前单独商品
		$address_id = I('address_id', 0, 'intval');
		$usersInfo = get_user_info($this->user_id);  // 用户
		if ($this->user_id == 0) exit(json_encode(array('status' => -1, 'msg' => '用户user_id不能为空', 'result' => '')));
		
		// 获取活动信息
		$where_spell_project['spell_project_id'] = \intval($spell_project_id);
		$where_spell_project['settlement_user_id'] = $this->user_id;
		if(!$spell_project = M('spell_project')->where($where_spell_project)->find()){
			$this->returnInfo(-1,"无此活动");
		}
		$goods_id = $spell_project['spell_goods_id'];
		// 获取商品信息
		$where['is_on_sale'] = 1;
		if($goods_id)$where['spell_goods_id'] = intval($goods_id);
		
		$goods_list = M('spell_goods')->where($where)->select();
		foreach($goods_list as $k => &$v){
			$v['original_img'] = parseMediaUrl($v['original_img']);
		}
		if(count($goods_list) <= 0) exit(json_encode(array('status' => -1, 'msg' => '无此商品信息', 'result' => '')));
		if($goods_id && count($goods_list) == 1)$goods_list = $goods_list[0];
		
		if($address_id < 1 ){
			$this->returnInfo(-1,"请填写收货地址");
		}
		$address = M('UserAddress')->where([
		    "address_id" => $address_id
		])->find();
		$order_sn = 'SPG' . $this->_createOrderSN();
		// 开启事务 下订单扣积分
		$Model = M();
		$Model->startTrans();
		// 添加订单
		// p($address);die;
		$addOrder['order_sn'] = $order_sn;// 订单编号
		$addOrder['user_id'] = $this->user_id;// 用户id
		$addOrder['order_status'] = 1;// 订单状态
		$addOrder['shipping_status'] = 0;// 发货状态
		$addOrder['pay_status'] = 1;// 支付状态
		$addOrder['consignee'] = $address['consignee'];// 收货人
		$addOrder['country'] = $address['country'];// 国家
		$addOrder['province'] = $address['province'];// 省份id
		$addOrder['city'] = $address['city'];// 城市id
		$addOrder['district'] = $address['district'];// 县
		$addOrder['twon'] = $address['twon'];// 街道
		$addOrder['address'] = $address['address'];// 详细地址
		$addOrder['zipcode'] = $address['zipcode'];// 邮编
		$addOrder['mobile'] = $address['mobile'];// 手机
		$addOrder['integral'] = 0;// 使用积分
		$addOrder['add_time'] = time();// 下单时间
		$addOrder['shipping_time'] = 0;// 最后新发货时间
		$addOrder['confirm_time'] = 0;// 收货确认时间
		$addOrder['pay_time'] = time();// 支付时间
		$addOrder['user_note'] = '';// 用户备注
		$addOrder['admin_note'] = '';// 管理员备注
		$addOrder['spell_goods_id'] = $goods_id;// 活动商品id
		$addOrder['spell_project_id'] = $spell_project_id;// 活动id
		// p( $goods_id);die;
		$orderRes = $Model->table('__SPELL_ORDER__')->add($addOrder);
		
		if($orderRes){
			$Model->commit();
			$this->returnInfo(1,"商品购买成功，请等待发货！");
		}else{
			$Model->rollback();
			$this->returnInfo(-1,"购买失败");
		}
	}
	
	// 生成订单号
	public function _createOrderSN()
	{
		return date('YmdHis', time()) . '' . $this->randNumber();
	}
	
	/**
	 * 获取随机位数数字
	 * @param integer $len 长度
	 * @return string
	 */
	public function randNumber($len = 4)
	{
		$chars = str_repeat('0123456789', 10);
		$chars = str_shuffle($chars);
		$str = substr($chars, 0, $len);
		return $str;
	}
	

}